#include "package.h"
#include <json/json.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

const char* package(struct package *p)
{
    struct json_object *json_obj,*protocol_obj,*field1_obj,*field2_obj,*field3_obj;
    
    //创建json对象
    json_obj = json_object_new_object();

    //c类型到json类型
    protocol_obj = json_object_new_int(p->protocol);
    field1_obj = json_object_new_string_len(p->field1,strlen(p->field1));
    field2_obj = json_object_new_string_len(p->field2,strlen(p->field2));
    field3_obj = json_object_new_string_len(p->field3,strlen(p->field3));

    //组合成一个json包
    json_object_object_add(json_obj,"protocol",protocol_obj);
    json_object_object_add(json_obj,"field1",field1_obj);
    json_object_object_add(json_obj,"field2",field2_obj);
    json_object_object_add(json_obj,"field3",field3_obj);

    //json转char*
    const char *str = json_object_to_json_string(json_obj);

    //销毁json对象
    json_object_put(protocol_obj);
    json_object_put(field1_obj);
    json_object_put(field2_obj);
    json_object_put(field3_obj);

    return str;
}

struct package* unpackage(const char *s,struct package *p)
{
    struct json_object *json_obj,*protocol_obj,*field1_obj,*field2_obj,*field3_obj;
   
    //字符串转json对象
    json_obj = json_tokener_parse(s);
    
    //对象获取
    protocol_obj = json_object_object_get(json_obj,"protocol");
    field1_obj = json_object_object_get(json_obj,"field1");
    field2_obj = json_object_object_get(json_obj,"field2");
    field3_obj = json_object_object_get(json_obj,"field3");

    //数据还原
    p->protocol = json_object_get_int(protocol_obj);
    strcpy(p->field1,json_object_get_string(field1_obj));
    strcpy(p->field2,json_object_get_string(field2_obj));
    strcpy(p->field3,json_object_get_string(field3_obj));

    //销毁json对象
    json_object_put(json_obj);
    json_object_put(protocol_obj);
    json_object_put(field1_obj);
    json_object_put(field2_obj);
    json_object_put(field3_obj);

    return p;
}

int rcv_package(int socket_c,char *buf,int size)
{
    printf("正在等待收包：\n");
    int i = 0,ret;
    bzero(buf,size);
    while((ret = read(socket_c,&buf[i],sizeof(buf[i]))) > 0){
        if(buf[i] == '}'){
            printf("收到%d的包：%s",socket_c,buf);
            return 0;
        }
        i++;
        if(i >= size-1){
            printf("rcv_package:装不下了，错误码-1\n");
            return -1;
        }
    }
    if(ret < 0){
        perror("rcv_package: read");
        return -2;
    }
    
    return 1;
}

int send_package(int socket_c,const char *buf)
{
    int i;
    printf("给%d发送%s\n",socket_c,buf);

    if((i = write(socket_c,buf,sizeof(char) * strlen(buf))) < 0){
        perror("write");
    }
    printf("发送成功\n");
    return i;
}